package com.lotter.invocation;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;

import com.lotter.common.exception.LotterCusException;
import com.lotter.common.util.StringUtil;
import com.lotter.model.user.OnlineUser;

public class StaticDataContext {
	
	// key  token   value  uid
	public static final Map<String,String> OnlineUserInfo
	     = new HashMap<String, String>();
	
	
	//初始化
	public static void init(List<OnlineUser> userList) throws LotterCusException{
		if(CollectionUtils.isEmpty(userList))
			return ;
		
		OnlineUserInfo.clear();
		String temp = "";
		for(OnlineUser onlineUser :userList){
			temp = onlineUser.getMobile()+","+onlineUser.getUid();
			OnlineUserInfo.put(onlineUser.getToken(), temp);
		}
	}
	
	//保存登录者信息  登录
	public static void put(OnlineUser onlineUser)throws LotterCusException{
		if(onlineUser == null || "".equals(onlineUser.getUid()) ||
				"".equals(onlineUser.getToken()))
			throw new LotterCusException();
		    //删除过时的数据
		    Iterator<Map.Entry<String, String>> it = OnlineUserInfo.entrySet().iterator();  
	        while(it.hasNext()){  
	        	   Map.Entry<String, String> entry=it.next();
	        	   String temp = entry.getValue().split(",")[1];
	        	   if(onlineUser.getUid().equals(temp))
	        		   it.remove();
	        }
		
		OnlineUserInfo.put(onlineUser.getToken(),onlineUser.getMobile()+","+onlineUser.getUid());
	}
	
	
	//删除登录者信息  退出
	public static void remove(String token) throws LotterCusException{
		if(StringUtil.isBlank(token))
			throw new LotterCusException();
		
		OnlineUserInfo.remove(token);
	}
	
	
	//判断是否存在
	public static Boolean isExist(String token) throws LotterCusException{
		if(StringUtil.isBlank(token))
			throw new LotterCusException();
		
		return OnlineUserInfo.containsKey(token);
	}
	
	
	//获取登录者手机号
	public static String onLineMobile(String token) throws LotterCusException{
		if(StringUtil.isBlank(token))
			return null ;
		String temp = OnlineUserInfo.get(token);
		return temp.split(",")[0];
	}
	
	//获取登录者手机号
	public static Long onLineUid(String token) throws LotterCusException{
		if(StringUtil.isBlank(token))
			return null ;
		String temp = OnlineUserInfo.get(token);
		return Long.parseLong(temp.split(",")[1]);
	}

}
